﻿using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BlackSurvivalCheat
{
    public class PatchHandler
    {
        public Type TargetType;
        public string TargetMethonName;
        public MethodInfo Prefix;
        public MethodInfo Postfix;
        public MethodInfo Transpiler;
        public void Patch(Harmony harmony)
        {
            harmony.Patch(AccessTools.Method(TargetType, TargetMethonName), GetHarmonyMethod(Prefix), GetHarmonyMethod(Postfix), GetHarmonyMethod(Transpiler));
        }

        private HarmonyMethod GetHarmonyMethod(MethodInfo method)
        {
            if (method == null)
                return null;
            return new HarmonyMethod(method);
        }

        public void Unpatch(Harmony harmony, HarmonyPatchType patchType = HarmonyPatchType.All)
        {
            List<MethodInfo> patches = new List<MethodInfo>();

            if ((patchType & HarmonyPatchType.Prefix) == HarmonyPatchType.Prefix)
            {
                if (Prefix != null)
                    patches.Add(Prefix);
            }
            if ((patchType & HarmonyPatchType.Postfix) == HarmonyPatchType.Postfix)
            {
                if (Postfix != null)
                    patches.Add(Postfix);
            }
            if ((patchType & HarmonyPatchType.Transpiler) == HarmonyPatchType.Transpiler)
            {
                if (Transpiler != null)
                    patches.Add(Transpiler);
            }

            if (patches.Count != 0)
                foreach (var i in patches)
                {
                    harmony.Unpatch(AccessTools.Method(TargetType, TargetMethonName), i);
                }
        }

        public enum HarmonyPatchType
        {
            All = 0b111,
            Prefix = 1,
            Postfix = 2,
            Transpiler = 4,
        }
    }
}
